package com.yvon.maple.service.base.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.yvon.boot.mybatis.BaseServiceImpl;
import com.yvon.maple.service.base.entity.FileRelate;
import com.yvon.maple.service.base.mapper.FileRelateMapper;
import com.yvon.maple.service.base.service.FileRelateService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : Yvon
 * @since : 2021-10-20
 */
@Service
public class FileRelateServiceImpl extends BaseServiceImpl<FileRelate, FileRelateMapper> implements FileRelateService {

    @Override
    public boolean incrSave(String businessKey, Set<Long> fileIds) {
        List<FileRelate> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(fileIds)) {
            fileIds.forEach(fileId ->
                    list.add(FileRelate.builder()
                    .fileId(fileId)
                    .businessKey(businessKey)
                    .build()));
        }
        return saveBatch(list);
    }

    @Override
    public boolean coverSave(String businessKey, Set<Long> fileIds) {
        removeBusinessKey(businessKey);
        List<FileRelate> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(fileIds)) {
            fileIds.forEach(fileId ->
                    list.add(FileRelate.builder()
                            .fileId(fileId)
                            .businessKey(businessKey)
                            .build()));
        }
        return saveBatch(list);
    }



    private boolean removeBusinessKey(String businessKey) {
        QueryWrapper<FileRelate> qw = new QueryWrapper<>();
        qw.eq("business_key", businessKey);
        return remove(qw);
    }


    @Override
    public List<Long> getFileIdsByBusinessKeys(Set<String> businessKeys) {
        if (CollUtil.isEmpty(businessKeys)) {
            return Lists.newArrayList();
        }
        List<FileRelate> list = lambdaQuery()
                .in(FileRelate::getBusinessKey, businessKeys)
                .list();

        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(FileRelate::getFileId).distinct().collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    @Override
    public List<Long> getFileIdsByBusinessKey(String businessKeys) {
        List<FileRelate> list = lambdaQuery()
                .eq(FileRelate::getBusinessKey, businessKeys)
                .list();

        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(FileRelate::getFileId).distinct().collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }
}
